package cn.bdqn;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class ShiroTester {
    @Test
    public void test(){
        //1创建领域
        IniRealm realm=new IniRealm("classpath:shiro.ini");
        //创建安全管理员
        DefaultSecurityManager securityManager=new DefaultSecurityManager();
        //领域赋值给SecuritManager
        securityManager.setRealm(realm);
        //绑定安全管理员
        SecurityUtils.setSecurityManager(securityManager);
        //获取subject
        Subject subject=SecurityUtils.getSubject();
        //创建toKen对象
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("dajun","888888");
        try {
            //登录
            subject.login(usernamePasswordToken);
            System.out.println("是否认证通过："+subject.isAuthenticated());
            System.out.println("身份信息："+subject.getPrincipal());
            if(subject.hasRole("管理员")){
                System.out.println("是管理员角色");
            }else{
                System.out.println("不是管理员角色");
            }
            if(subject.isPermitted("user:view")){
                System.out.println("拥有操作用户查看权限");
            }else{
                System.out.println("没有操作用户查看权限");
            }
        } catch (AuthenticationException e) {//登录失败出现的异常
            e.printStackTrace();
        }
    }

    public void testMD5(){
        String password="123456";
        String salt="czkt";
        Md5Hash md5Has=new Md5Hash(password,salt,2);
        System.out.println(md5Has.toString());
    }

}
